package cn.conac.rc.ofs.rest;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import cn.conac.rc.framework.utils.BeanMapper;
import cn.conac.rc.framework.utils.StringUtils;
import cn.conac.rc.framework.vo.ResultPojo;
import cn.conac.rc.ofs.entity.AppFilesEntity;
import cn.conac.rc.ofs.entity.ApprovalEntity;
import cn.conac.rc.ofs.entity.FileEntity;
import cn.conac.rc.ofs.service.AppFilesService;
import cn.conac.rc.ofs.service.ApprovalService;
import cn.conac.rc.ofs.service.FileService;
import cn.conac.rc.ofs.service.OrganizationBaseService;
import cn.conac.rc.ofs.vo.AppdateCheckVo;
import cn.conac.rc.ofs.vo.ApprovalVo;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value="approval/")
public class ApprovalController {

	@Autowired
	OrganizationBaseService baseService;

	@Autowired
	ApprovalService appService;

	@Autowired
	AppFilesService appFilesService;

	@Autowired
	FileService fileService;

	@ApiOperation(value = "批文详情", httpMethod = "GET", response = ApprovalEntity.class, notes = "根据id获取批文详情")
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> detail(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "id", required = true) @PathVariable("id") Integer id) throws Exception{
		// 声明返回结果集
		ResultPojo result = new ResultPojo();
		// service调用
		ApprovalEntity approval = appService.findById(id);
		ApprovalVo approvalVo = new ApprovalVo();
		List<FileEntity> fileList = new ArrayList<FileEntity>();
		if(null != approval) {
			BeanMapper.copy(approval, approvalVo);
			
			List<AppFilesEntity> apeList = appFilesService.listByBaseId(approval.getId());
			
			for(AppFilesEntity ape : apeList){
				fileList.add(fileService.findById(ape.getId()));
			}
		}
		approvalVo.setFilelist(fileList);
		
		// 结果集设定
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(approvalVo);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "获取批文信息列表", httpMethod = "GET", response = ApprovalVo.class, notes = "根据orgId获取批文信息列表")
	@RequestMapping(value = "list/{orgId}", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> findApprovalListByOrgId(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "orgId", required = true) @PathVariable("orgId") Integer orgId) throws Exception{
		// 声明返回结果集
		ResultPojo result = new ResultPojo();
		// service调用
		List<ApprovalEntity> appList = appService.findByOrgId(orgId);
		List<ApprovalVo> appVoList = new  ArrayList<ApprovalVo>();
		for(ApprovalEntity app: appList){
			ApprovalVo appVo = new ApprovalVo();
			BeanMapper.copy(app, appVo);

			// 获取该批文对应部门是否为简要信息
			String isSimple = baseService.findById(app.getId()).getIsSimple();
			appVo.setIsSimple(isSimple);
			
			// 获取批文文件相关信息
			List<AppFilesEntity> apeList = appFilesService.listByBaseId(app.getId());
			List<FileEntity> fileList = new ArrayList<FileEntity>();
			for(AppFilesEntity ape : apeList){
				fileList.add(fileService.findById(ape.getId()));
			}
			appVo.setFilelist(fileList);
			appVoList.add(appVo);
		}
		// 结果集设定
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(appVoList);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "获取批文信息列表（带主批文）", httpMethod = "GET", response = ApprovalVo.class, notes = "根据orgId获取主批文信息列表")
	@RequestMapping(value = "main/{orgId}/list", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> detailForMainApproval(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "orgId", required = true) @PathVariable("orgId") Integer orgId) throws Exception{
		// 声明返回结果集
		ResultPojo result = new ResultPojo();
		// service调用
		List<ApprovalEntity> appList = appService.findDetailByOrgId(orgId);
		List<ApprovalVo> appVoList = new  ArrayList<ApprovalVo>();
		boolean isRedefinedFlg = false;// 判断isRedefined标识是否已经放入
		for(ApprovalEntity app: appList){

			if(!isRedefinedFlg || !"1".equals(app.getIsRedefined())){
				ApprovalVo appVo = new ApprovalVo();
				BeanMapper.copy(app, appVo);

				List<AppFilesEntity> apeList = appFilesService.listByBaseId(app.getId());
				List<FileEntity> fileList = new ArrayList<FileEntity>();
				for(AppFilesEntity ape : apeList){
					fileList.add(fileService.findById(ape.getId()));
				}
				appVo.setFilelist(fileList);
				appVoList.add(appVo);
			}

			// 去除其他同一appDate的其他数据（因为updateTime只取最新的，其他的不要）
			if("1".equals(app.getIsRedefined())){
				isRedefinedFlg = true;
			}
		}
		// 结果集设定
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(appVoList);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "新增或者更新数据", httpMethod = "POST", response = ApprovalEntity.class, notes = "保存资源到数据库")
	@RequestMapping(value = "{submitType}", method = RequestMethod.POST)
	public ResponseEntity<ResultPojo> save(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "提交类别", required = true) @PathVariable("submitType") String submitType,
			@ApiParam(value = "保存对象", required = true) @RequestBody ApprovalEntity entity) throws Exception {
		// 声明返回结果集
		ResultPojo result = new ResultPojo();

		// 数据格式校验
		if(!"0".equals(submitType)){
			String valMsg = appService.validate(entity);
			if (valMsg != null) {
				result.setCode(ResultPojo.CODE_FORMAT_ERR);
				result.setMsg(valMsg);
				return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
			}
		}

		// 业务操作
		appService.save(entity);

		// 结果集设定
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(entity);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "物理删除", httpMethod = "POST", response = String.class, notes = "根据id物理删除资源")
	@RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
	public ResponseEntity<ResultPojo> delete(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "id", required = true) @PathVariable("id") Integer id) {
		// 声明返回结果集
		ResultPojo result = new ResultPojo();
		// service调用
		appService.delete(id);
		// 结果集设定
		result.setCode(ResultPojo.CODE_SUCCESS);
		result.setResult(id);
		result.setMsg(ResultPojo.MSG_SUCCESS);
		return new ResponseEntity<ResultPojo>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "历史沿革批文时间校验", httpMethod = "GET", response = String.class, notes = "校验新添加批文时间是否在新建部门批文时间之前")
	@RequestMapping(value = "{orgId}/checkAppDateBefore/{newAppDate}", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> checkAppDateBefore(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "orgId", required = true) @PathVariable("orgId") Integer orgId,
			@ApiParam(value = "newAppDate", required = true) @PathVariable("newAppDate") String newAppDate) {
		// 声明返回结果集
		ResultPojo result = new ResultPojo();
		// 参数判断
		if(orgId == null || StringUtils.isBlank(newAppDate)){
			result.setCode(ResultPojo.CODE_FAILURE);
			result.setMsg(ResultPojo.MSG_FAILURE);
		} else {
			// service调用
			AppdateCheckVo checkVo = appService.checkAppDateBefore(orgId,newAppDate);
			// 结果集设定
			result.setCode(ResultPojo.CODE_SUCCESS);
			result.setResult(checkVo);
			result.setMsg(ResultPojo.MSG_SUCCESS);
		}
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

	@ApiOperation(value = "部门管理批文时间校验", httpMethod = "GET", response = String.class, notes = "校验新添加批文时间是否在新建部门批文时间之后")
	@RequestMapping(value = "{orgId}/checkAppDateAfter/{newAppDate}", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> checkAppDateAfter(HttpServletRequest request, HttpServletResponse response,
			 @ApiParam(value = "orgId", required = true) @PathVariable("orgId") Integer orgId,
			 @ApiParam(value = "newAppDate", required = true) @PathVariable("newAppDate") String newAppDate) {
		// 声明返回结果集
		ResultPojo result = new ResultPojo();
		// 参数判断
		if(orgId == null || StringUtils.isBlank(newAppDate)){
			result.setCode(ResultPojo.CODE_FAILURE);
			result.setMsg(ResultPojo.MSG_FAILURE);
		} else {
			// service调用
			AppdateCheckVo checkVo = appService.checkAppDateAfter(orgId,newAppDate);
			// 结果集设定
			result.setCode(ResultPojo.CODE_SUCCESS);
			result.setResult(checkVo);
			result.setMsg(ResultPojo.MSG_SUCCESS);
		}
		return new ResponseEntity<>(result, HttpStatus.OK);
	}

}